package com.zw.blog.web;

import com.zw.blog.po.Tag;
import com.zw.blog.po.Type;
import com.zw.blog.service.BlogService;
import com.zw.blog.service.TagService;
import com.zw.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    //@GetMapping("/{id}/{name}") //传入路径参数
    @GetMapping("/")
    public String index(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        Model model, HttpSession session) {
        model.addAttribute("page", blogService.listBlogPublished(pageable, session));
        List<Type> types = typeService.listTypeTop(6);
        // 有问题 得优化
        for (Type type : types) {
            type.initPublishedBlogs(session);
        }

        List<Tag> tags = tagService.listTagTop(10);
        for (Tag tag : tags) {
            tag.initPublishedBlogs(session);
        }
        model.addAttribute("types", types);
        model.addAttribute("tags", tags);
        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(8));
        return "index";
    }

    @PostMapping("/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model, HttpSession session) {
        model.addAttribute("page", blogService.listBlog("%" + query + "%", session, pageable));
        model.addAttribute("query", query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {
        model.addAttribute(blogService.getAndConvert(id));
        //model.addAttribute(blogService.getBlog(id));
        return "blog";
    }

    @GetMapping("/about")
    public String about() {
        return "about";
    }

    @GetMapping("/footer/newBlogs")
    public String newBlogs(Model model) {
        model.addAttribute("newBlogs", blogService.listRecommendBlogTop(3));
        return "_fragments :: newBlogList";
    }
}
